package com.dididoctor.patient.Activity.Service.ServiceDetail;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.dididoctor.patient.Activity.ConstantValue;
import com.dididoctor.patient.Activity.Doctor.Doctordetail.Prdbuy;
import com.dididoctor.patient.Activity.MakeCall.MakeCallOkActivity;
import com.dididoctor.patient.MV.EduActivity;
import com.dididoctor.patient.R;
import com.dididoctor.patient.Utils.SharedPreferencesUtils;
import com.dididoctor.patient.Utils.Util;
import com.dididoctor.patient.ZFB.PayResult;
import com.dididoctor.patient.ZFB.SignUtils;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @version 2.0
 * @类描述：
 * @项目名称：ddgh
 * @类名称： ServiceDetailActivity
 * @包名称： com.dididoctor.patient.Activity.Service.ServiceDetail
 * @创建人： zhanjunjie
 * @创建时间：2016/4/6 10:29
 * @修改人：
 * @修改时间：2016/4/6 10:29
 * @修改备注： new parent class(用一句话描述修改了什么)
 */
public class ServiceDetailActivity extends EduActivity implements ServiceDetailView {

    private WebView mWvService;
    private RelativeLayout mRlzifu;
    private ServiceDetailPresenter presenter;
    private String prdId = "";
    private String webUrl = "";
    private ServiceDetail serviceDetail = new ServiceDetail();
    private TextView tv_prdname, tv_prdprice;
    private Prdbuy prdbuy = new Prdbuy();
    private Button btn_loginout;
    private boolean isprice = false;
    //支付方式
    private String type = "2";
    /**
     * 支付
     */
    // 商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL5AypQkeMlT97sa\n" +
            "+B9KnLxnNSFS9jmkmG57grcfiznoZpne2VqTrgZA2WvU3vHIoS6P6dMCbLRBQrz1\n" +
            "PyYg1tfq1w/HGb5RSYkjYCCeYXdqsVG1TcvveWsczcuTZWv7+OC/lGnEZOvn6KMr\n" +
            "Cp1n2X3JQJsCfiDxILW4+WbvnKUxAgMBAAECgYAp0Un1t/KIphksmifxkM/UpYbL\n" +
            "FVYjo2cR2boIkDlk+A0dQxtZSl6U50oi5n4+fM/Y0S8e/0hvcmy95dYEhnFSUOx1\n" +
            "MJMU/fQJaduy4av5dugFTp4Kj7UfbQXT5ys0wBY5TsA708j7Gn/L8OwdtWpwgsWP\n" +
            "bw5hAu5ydTCL4SCwtQJBAO7n6Zg7solE+mXiYybfaGtHWrH01wd3WbAs/cgyG5L4\n" +
            "6Z2oBdys0XjMLeqAJWqXSX4+SclYNx5H2AyMG6LS5/cCQQDL3bIG+6lFzgKPQ+Xt\n" +
            "GvaLzQ46rpzVrGOGzRwdAE+ffPIxRLj+ykSP3bLafsygQdUWNVX+Kt7V0xnaywCq\n" +
            "PSIXAkEArDiqgH+oeKQtDf1hFMjAcXWCv/6MdGlpUkNcv1C/5/dgEbLqZuZ+KuKl\n" +
            "xwKR9oERDdzBPFBHi6Cm8oSd94aqiQJAQQqpGts9xTyVynmCKOSaVj4E1SoSdYV7\n" +
            "d22HE6WewaaOarOfRgLoXvH/dwBPbq2yO1Sm6+FnmNayAAEWZDn+3wJBAN/zOQzB\n" +
            "TAk4GT1MIE8mRRCFxSZYQmc5oRYpl4dp+ymcDdEB8LJsK+0o/phA+6nm/mS6vLjD\n" +
            "eda6qHepXLN43eU=\n";

    private static final int SDK_PAY_FLAG = 1;

    //微信支付
    private IWXAPI api;

    //接收支付成功广播
    private PayOkRecedir myReceiver;

    @Override
    public void init() {
        api = WXAPIFactory.createWXAPI(this, ConstantValue.APP_ID, false);
        api.registerApp(ConstantValue.APP_ID);
        initmyBroadcast();
        prdId = getIntent().getStringExtra("prdId");

        mRlzifu = (RelativeLayout) findViewById(R.id.rel_zifufangsi);
        mWvService = (WebView) findViewById(R.id.webview);

        mWvService.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //  重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
                view.loadUrl(url);
                return true;
            }
        });
        tv_prdname = (TextView) findViewById(R.id.tv_prdname);
        tv_prdprice = (TextView) findViewById(R.id.tv_prdprice);
        btn_loginout = (Button) findViewById(R.id.btn_loginout);
        findViewById(R.id.btn_loginout).setOnClickListener(this);
        findViewById(R.id.ll_zifu).setOnClickListener(this);
        findViewById(R.id.ll_weixin).setOnClickListener(this);
        mRlzifu.setOnClickListener(this);
        if (Util.isEmpty(prdId)) {
            webUrl = getIntent().getStringExtra("webUrl");
            btn_loginout.setVisibility(View.GONE);
            mWvService.loadUrl(webUrl);
            setText(R.id.tv_title, "活动详情");

        } else {
            setText(R.id.tv_title, "服务详情");
            presenter = new ServiceDetailPresenter(this, this);
            presenter.getServicedetail(prdId);
        }
    }

    private void initmyBroadcast() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("PayOkRecedir");
        myReceiver = new PayOkRecedir();
        registerReceiver(myReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(myReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class PayOkRecedir extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("PayOkRecedir".equals(action)) {
                int code = intent.getIntExtra("code", -1);
                if (code == 0) {
                    presenter.paysuccess("5", prdbuy.getPayId());
                }
            }
        }
    }


    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.btn_loginout:
                if (!"".equals(serviceDetail.getPrize())) {
                    isprice = true;
                    mRlzifu.setVisibility(View.VISIBLE);
                } else {
                    isprice = false;
                    presenter.prdbuy(prdId, serviceDetail.getPrize(), "3", type, "", "", "");
                }

                break;
            case R.id.ll_zifu:
                type = "1";
                presenter.prdbuy(prdId, serviceDetail.getPrize(), "3", type, "", "", "");
                break;
            case R.id.ll_weixin:
                type = "2";
                presenter.prdbuy(prdId, serviceDetail.getPrize(), "3", type, "", "", "");
                break;
            case R.id.rel_zifufangsi:
                mRlzifu.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_service_detail);
    }

    @Override
    public void getServiceDetail(ServiceDetail serviceDetail) {
        if (serviceDetail != null) {
            this.serviceDetail = serviceDetail;
            mWvService.loadUrl(serviceDetail.getWebUrl());
            tv_prdname.setText(serviceDetail.getName());
            tv_prdprice.setText(serviceDetail.getPrize());
            if ("0".equals(serviceDetail.getIsallow())) {//不可购买
                btn_loginout.setVisibility(View.GONE);
            } else {
                btn_loginout.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void getServiceFail() {

    }

    @Override
    public void prdbuy(Prdbuy prdbuy) {
        if (prdbuy != null) {
            this.prdbuy = prdbuy;
            if (isprice) {
                if ("1".equals(type)) {
                    pay(prdbuy);
                } else {
                    weixinpay(prdbuy);
                }

            } else {
                mRlzifu.setVisibility(View.GONE);
                Intent intent = new Intent(this, MakeCallOkActivity.class);
                intent.putExtra("type", "1");
                startActivity(intent);
                finish();
            }
        }

    }

    /**
     * 微信支付
     *
     * @param prdbuy
     */
    public void weixinpay(Prdbuy prdbuy) {
        PayReq req = new PayReq();
//        descr = {String@830056874488} "签约医生"
//        nonceStr = {String@830056797024} "1405122771"
//        notifyurl = {String@830035547520} "http://192.168.1.181:8080/doctor/pay/weipayresult.do"
//        partnerId = {String@830056775728} "1333270401"
//        payId = {String@830061191736} "S101461823512"
//        prepayId = {String@830056874664} "wx2016042814051254615850620047017099"
//        sign = {String@830061191960} "516164A67AADA2907B1BAB098E44BDE4"
//        timeStamp = {String@830056775544} "1461823512"
        if (api != null) {
            req.appId = ConstantValue.APP_ID;
            req.partnerId = prdbuy.getPartnerId();
            req.prepayId = prdbuy.getPrepayId();
            req.nonceStr = prdbuy.getNonceStr();
            req.timeStamp = prdbuy.getTimeStamp();
            req.packageValue = "Sign=WXPay";
            req.sign = prdbuy.getSign();
//            req.extData = "app data"; // optional
            Toast.makeText(ServiceDetailActivity.this, "正常调起支付", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.sendReq(req);
        }
    }

    @Override
    public void prdbuyfail() {
        showToastMessage("请求失败");
    }

    @Override
    public void paysuccess() {
        mRlzifu.setVisibility(View.GONE);
        Intent intent = new Intent(this, MakeCallOkActivity.class);
        intent.putExtra("type", "1");
        startActivity(intent);
        finish();
    }

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void pay(final Prdbuy prdbuy) {

        String orderInfo = getOrderInfo(prdbuy);

        /**
         * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
         */
        String sign = sign(orderInfo,prdbuy.getPrivateKey());
        try {
            /**
             * 仅需对sign 做URL编码
             */
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        /**
         * 完整的符合支付宝参数规范的订单信息
         */
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType(prdbuy.getSign_type());

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(ServiceDetailActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * create the order info. 创建订单信息
     */
    private String getOrderInfo(final Prdbuy prdbuy) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + prdbuy.getPartner() + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + prdbuy.getSeller_id() + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + prdbuy.getOut_trade_no() + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + prdbuy.getSubject() + "\"";

//        // 商品详情
//        orderInfo += "&body=" + "\"" + prdbuy.getSubject() + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + prdbuy.getTotal_fee() + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + prdbuy.getNotify_url() + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=" + "\"" + prdbuy.getService() + "\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=" + "\"" + prdbuy.getPayment_type() + "\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=" + "\"" + prdbuy.get_input_charset() + "\"";


        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
//        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
//        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    private String sign(String content,String privateKey) {
        return SignUtils.sign(content, privateKey);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    private String getSignType(String sign_type) {
        return "sign_type=" + "\"" + sign_type + "\"";
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        presenter.paysuccess("5", prdbuy.getPayId());
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(ServiceDetailActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(ServiceDetailActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mRlzifu.getVisibility() == View.VISIBLE ) {
                mRlzifu.setVisibility(View.GONE);
            } else {
                finish();
            }
        }
        return true;
    }
}
